<template>
  <div>
		<van-nav-bar  title="商家入驻" left-arrow @click-left="$utils.back($route.path)" />
		<div class="register-form pd-24 mg-24 bg-white">
      <van-cell-group class="apply_main fs-30">
				<van-field
					class="fs-30"
					v-model="model.factoryName.value"
					required
					clearable
					:label="model.factoryName.label"
					placeholder="请输入厂家名称"
				/>
				<van-field
					class="fs-30"
					v-model="model.name.value"
					required
					clearable
					:label="model.name.label"
					placeholder="请输入店铺名称"
				/>
				<van-field
					class="fs-30"
					v-model="model.contactTel.value"
					required
					clearable
					:label="model.contactTel.label"
					placeholder="请输入手机号码"
				/>
				<van-field
					class="fs-30"
          v-model="model.password.value"
          type="password"
          :label="model.password.label"
          placeholder="请设置登录密码"
          required
          clearable
        />
				<van-field
				 	class="fs-30"
          v-model="model.validCode.value"
          required
          center
          clearable
          :label="model.validCode.label"
          placeholder="请输入验证码"
        >
          <van-button
            slot="button"
            size="small"
            type="info"
            :disabled="codeDisabled"
            @click="sendCode"
          >{{codeTxt}}</van-button>
        </van-field>
				<van-field
					class="fs-30"
					v-model="model.contactName.value"
					required
					clearable
					:label="model.contactName.label"
					placeholder="请输入联系人"
				/>
				<van-field
					class="fs-30"
					readonly
					clickable
					right-icon="arrow"
					name="area"
					required
					:value="model.regionNames.value"
					label="地区"
					placeholder="点击选择地区"
					:rules="[{ required: true, message: ' ' }]"
					@click="showArea = true"
				/>
				<div class="project mr-24 pb-24">
					<div class="apply_title left-star">详细地址</div>
					<van-field v-model="model.contactAddress.value" type="textarea" class="pl-10 fs-30 mt-15 remark" placeholder="请输入详细地址" />
				</div>
				<div class="project mr-24 pb-24">
					<div class="apply_title left-star">店铺LOGO</div>
					<van-cell class="ptb-20 pr-30">
						<van-uploader
							slot="title"
							v-model="logo"
							class="advertPictures"
							:max-count="1"
							:after-read="(file)=>{afterRead(file,'logo')}"
							preview-size="2rem"
							@delete="(file,detail)=>{afterDelete(file,detail,'logo')}"
						/>
					</van-cell>
				</div>
			</van-cell-group>
		</div>
		<div class="plr-40 ptb-16 bg-white fixed-bottom" v-if="model.ID === 0 || model.state === 2">
      <van-button size="large" class="bg-physio-primary1 color-white br-44" @click="submit">提交申请</van-button>
    </div>
		<van-popup v-model="showArea" position="bottom">
      <areaSelect :address-data="pageData" @pickArea="pickArea" />
    </van-popup>
		<van-popup v-model="showTips" :close-on-click-overlay="isclose" class="services">
			<div class="unartificer">
					<div class="fs-28 tac">您没有操作权限</div>
			</div>
		</van-popup>
	</div>
</template>
<script>
import { Toast } from 'vant'
import { upLoad } from 'api/upload'
import { SendSmsNoVerifyCode } from 'api/member'
import areaSelect from 'components/address/areaSelect'
import { ApplySupplierByUser, GetSupplierInfoByShopUserId } from 'api/purchase'
import { GetBusinessFunction } from 'api/businessSetting'
import { GetUserStore } from 'api/store'
export default {
	components: {
    areaSelect,
  },
	data() {
    return {
      avar: [],
      logo: [],
      model: {
        factoryName: {
          label: '厂家名称',
          value: '',
          require: true,
          requireMessage: '请输入厂家名称'
        },
				name: {
          label: '店铺名称',
          value: '',
          require: true,
          requireMessage: '请输入店铺名称'
        },
        contactTel: {
          label: '手机号',
          value: '',
          require: true,
          requireMessage: '请输入手机号码',
					pattern: /^1[3456789]\d{9}$/,
          patternMessage: '请输入正确的手机号'
        },
				password: {
          label: '登录密码',
          value: '',
          require: true,
          requireMessage: '请设置登录密码',
          minLength: 6
        },
				validCode: {
          label: '短信验证码',
          value: '',
          require: true,
          requireMessage: '请输入短信验证码'
        },
        contactName: {
          label: '联系人',
          value: '',
          require: true,
          requireMessage: '请输入联系人',
        },
				regionNames: {
          label: '地区',
          value: '',
          require: true,
          requireMessage: '请选择地区',
        },
				contactAddress: {
          label: '详细地址',
          value: '',
          require: true,
          requireMessage: '请输入详细地址',
        },
        logo: {
          label: '店铺LOGO',
          value: [],
          minLength: 1,
          minLengthMessage: '请上传店铺LOGO'
        },
				validType: 8,
				provinceName: '',
				provinceId: 0,
				cityName: '',
				cityId: 0,
				regionName: '',
				regionId: 0,
				streetName: '',
				streetId: '',
      },
      sortList: [],
      identify: {
        // 随机产生验证码的字符串
        identifyCodes: '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        identifyCode: ''
      },
      codeDisabled: false,
      codeTxt: '发送验证码',
			showArea: false,
			pageData: {},
			showTips: false,
			isclose: false,
    }
  },
	created(){
		this.GetUserStore()
		this.GetBusinessFunction()
		this.GetSupplierInfoByShopUserId()
	},
	methods: {
		GetUserStore(){
			GetUserStore().then(res => {
				if(!res.Data || res.Data.Status !== 1){
					this.showTips = true
				}
			})
		},
		GetBusinessFunction(){
      GetBusinessFunction(203).then(res => {
        if (res) {
          this.switch203 = res.Data[0].Value;
					if(this.switch203 === 0){
						this.showTips = true
					}
        }
      })
    },
		GetSupplierInfoByShopUserId(){
			GetSupplierInfoByShopUserId().then(res => {
				if(res.Data){
					const data = res.Data
					const _model = this.model
					_model.name.value = data.Name
					_model.contactTel.value = data.ContactTel
					_model.factoryName.value = data.FactoryName
					_model.password.value = data.Password
					_model.contactName.value = data.ContactName
					_model.provinceName = data.ProvinceName
					_model.provinceId = data.ProvinceId
					_model.cityName = data.CityName
					_model.cityId = data.CityId
					_model.regionName = data.RegionName
					_model.regionId = data.RegionId
					_model.streetName = data.StreetName
					_model.streetId = data.StreetId
					_model.contactAddress.value = data.ContactAddress
					if(data.ProvinceName){
						_model.regionNames.value = ( data.ProvinceName || '' ) + '-' + ( data.CityName|| '' ) + '-' + ( data.RegionName || '' ) + '-' + ( data.StreetName || '')
					}
					if (res.Data.Logo) {
						res.Data.Logo = res.Data.Logo.split(',')
						for (let i = 0, len = res.Data.Logo.length; i < len; i++) {
							if(res.Data.Logo[i] != ''){
								this.logo.push({
									url: this.$webInfo.ImgDomain + res.Data.Logo[i]
								})
							}
						}
						this.model.logo.value = res.Data.Logo
					}
					_model.ID = data.ID
					_model.state = data.State
					if(data.ID > 0 && data.State !== 2){
						this.codeDisabled = true
					}
				}
			})
		},
    afterRead(file, type) {
      if (file.length) {
        for (let i = 0, len = file.length; i < len; i++) {
          upLoad({
            Content: this.$utils.getCaption(file[i].content, 'base64,'),
            FileType: this.$utils.getCaption(file[i].file.type, '/')
          }).then(res => {
            if (res) {
              if (type == 'logo') {
                this.model.logo.value.push(res.Data.Path)
              }
            }
          })
        }
      } else {
        upLoad({
          Content: this.$utils.getCaption(file.content, 'base64,'),
          FileType: this.$utils.getCaption(file.file.type, '/')
        }).then(res => {
          if (res) {
            if (type == 'logo') {
              this.model.logo.value.push(res.Data.Path)
            }
          }
        })
      }
    },
		afterDelete(file, detail, type) {
			if (type == 'logo') {
				this.model.logo.value.splice(detail.index, 1)
      }
			console.log(this.model.logo,"近期照")
    },
    // 验证码部分end
    sendCode() {
      let self = this
      if (!/^1[3456789]\d{9}$/.test(self.model.contactTel.value)) {
        Toast('请输入正确的手机号')
      } else {
        SendSmsNoVerifyCode({tel:self.model.contactTel.value,validType: 8}).then(res => {
          //console.log(res);
          if (res) {
            Toast.success('短信验证码已发送')
            self.codeDisabled = true
            let time = 60
            self.codeTxt = time + 's'
            let clock = setInterval(() => {
              if (time == 1) {
                self.codeDisabled = false
                self.codeTxt = '发送验证码'
                clearInterval(clock)
              } else {
                self.codeTxt = --time + 's'
              }
            }, 1000)
          }
        })
      }
    },
    // 验证码部分start
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
      this.identify.identifyCode = ''
      this.makeCode(this.identify.identifyCodes, 4)
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identify.identifyCode += this.identify.identifyCodes[this.randomNum(0, this.identify.identifyCodes.length)]
      }
    },
    // 验证码部分end
    // 保存地图详细地址
    confirmAmap(dataModel) {
      //console.log(this.model);
    },
    // 选择商家类型
    //onConfirm(item) {
    //  this.model.bussinessType.value = item.text
    //  this.model.bussinessType.id = item.value
    //  this.showBussinessType = false
    //},
    // 营业时间选择
    TimeSelect(item, type) {
      if (type == 'start') {
        this.model.startTime.value = item
        this.startTime = false
      } else {
        this.model.endTime.value = item
        this.endTime = false
      }
    },
    // 商区选择
    areaSelect(item) {
      //console.log(item);
      if (this.model.area.AreaId != item[2].code) {
        if (item[2].code) {
          this.model.area.value = item[0].name + '-' + item[1].name + '-' + item[2].name
        } else {
          this.model.area.value = item[0].name + '-' + item[1].name
        }
        this.model.area.ProvinceName = item[0].name
        this.model.area.ProvinceId = item[0].code
        this.model.area.CityName = item[1].name
        this.model.area.CityId = item[1].code
        this.model.area.AreaName = item[2].name
        this.model.area.AreaId = item[2].code
        this.model.address.value = ''
      }
      this.showArea = false
    },
    submit() {
      let self = this
      // 表单验证
      if (self.$utils.formValidate(self.model).valid) {
				ApplySupplierByUser(self.model).then(res => {
            if (res.Data) {
              this.$toast({
                type: 'success',
                message: '已提交申请审核',
                forbidClick: true,
                onClose: function() {
                  self.$router.back()
                }
              })
							//window.location.href = this.$LocalDomain + '/m/home/union'
            }else{
							this.$toast.fail({
								message: res.Msg,
								icon: 'close'
							})
						}
          })
      } else {
        this.$toast(self.$utils.formValidate(self.model).msg)
      }
    },
		
		// 确认选择省市区
		pickArea(areaObj) {
      console.log(areaObj)
      this.model.provinceName = areaObj.ProvinceName
      this.model.provinceId = areaObj.ProvinceId
      this.model.cityName = areaObj.CityName
			//this.city = areaObj.CityName
      this.model.cityId = areaObj.CityId
      this.model.regionName = areaObj.AreaName
      this.model.regionId = areaObj.AreaId
      this.model.streetName = areaObj.StreetName
      this.model.streetId = areaObj.StreetId
      this.model.regionNames.value = (this.model.provinceName || '') + '-' + (this.model.cityName || '') + '-' + (this.model.regionName || '') + '-' + (this.model.streetName || '')
      this.showArea = false
    },
  },
}
</script>
<style lang="scss" scoped>
	.remark{
		background: #f7f7f7;
		padding-left: 32px !important;
	}	
	.project{
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		border-bottom: 1px solid #ebedf0;
		margin-left: 10px;
	}
	.apply_title{
		margin: 20px 0 0 5px;
		font-size: 30px;
		position: relative;
	}
	.project:last-child{
		border-bottom: none;
	}
	[class*=van-hairline]::after {
  	border: none;
	}
	.project{
		.van-cell{
			padding-left: 0;
		}
	}
	.left-star{
		padding-left: 15px;
		&::before{
			content: "*";
			color: #FF0202;
			position: absolute;
			font-size: 28px;
			top: 5px;
			left: 0;
		}
	}
	.services{
		width: 60%;
		border-radius: 12px;
	}
	.unartificer{
		background: #fff;
		padding: 24px;
	}
	.disTitle {
		color: #c8c9cc;
	}
</style>
